<template>
  <div class="notifications">
    <div class="notifications-header">
      <h2>🔔 消息提醒</h2>
      <div class="header-actions">
        <el-button type="text" @click="markAllAsRead" :disabled="unreadCount === 0">
          <el-icon><Check /></el-icon>
          全部已读
        </el-button>
        <el-button type="text" @click="refreshNotifications">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 消息统计 -->
    <div class="notifications-stats">
      <div class="stat-card" @click="filterByType('all')" :class="{ active: currentFilter === 'all' }">
        <div class="stat-icon all">
          <el-icon><Bell /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-count">{{ notifications.length }}</span>
          <span class="stat-label">全部消息</span>
        </div>
      </div>
      
      <div class="stat-card" @click="filterByType('like')" :class="{ active: currentFilter === 'like' }">
        <div class="stat-icon like">
          <el-icon><Star /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-count">{{ likeNotifications.length }}</span>
          <span class="stat-label">点赞提醒</span>
          <span v-if="getUnreadCountByType('like') > 0" class="unread-badge">
            {{ getUnreadCountByType('like') }}
          </span>
        </div>
      </div>
      
      <div class="stat-card" @click="filterByType('dislike')" :class="{ active: currentFilter === 'dislike' }">
        <div class="stat-icon dislike">
          <el-icon><CircleClose /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-count">{{ dislikeNotifications.length }}</span>
          <span class="stat-label">点踩提醒</span>
          <span v-if="getUnreadCountByType('dislike') > 0" class="unread-badge">
            {{ getUnreadCountByType('dislike') }}
          </span>
        </div>
      </div>
      
      <div class="stat-card" @click="filterByType('comment')" :class="{ active: currentFilter === 'comment' }">
        <div class="stat-icon comment">
          <el-icon><ChatDotRound /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-count">{{ commentNotifications.length }}</span>
          <span class="stat-label">评论提醒</span>
          <span v-if="getUnreadCountByType('comment') > 0" class="unread-badge">
            {{ getUnreadCountByType('comment') }}
          </span>
        </div>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="notifications-list">
      <div v-if="filteredNotifications.length > 0" class="notifications-container">
        <div
          v-for="notification in filteredNotifications"
          :key="notification.id"
          class="notification-item"
          :class="{ unread: !notification.read, [notification.type]: true }"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-avatar">
            <el-avatar :size="40" :src="notification.fromUser.avatar" />
            <div class="notification-type-icon" :class="notification.type">
              <el-icon v-if="notification.type === 'like'"><Star /></el-icon>
              <el-icon v-else-if="notification.type === 'dislike'"><CircleClose /></el-icon>
              <el-icon v-else-if="notification.type === 'comment'"><ChatDotRound /></el-icon>
            </div>
          </div>
          
          <div class="notification-content">
            <div class="notification-header">
              <span class="user-name">{{ notification.fromUser.name }}</span>
              <span class="notification-time">{{ formatTime(notification.timestamp) }}</span>
            </div>
            
            <div class="notification-message">
              <span v-if="notification.type === 'like'">
                点赞了你的帖子
              </span>
              <span v-else-if="notification.type === 'dislike'">
                点踩了你的帖子
              </span>
              <span v-else-if="notification.type === 'comment'">
                评论了你的帖子
              </span>
              
              <span class="post-preview">"{{ getPostPreview(notification.postContent) }}"</span>
            </div>
            
            <div v-if="notification.type === 'comment' && notification.commentContent" class="comment-content">
              {{ notification.commentContent }}
            </div>
          </div>
          
          <div class="notification-actions">
            <el-button
              v-if="!notification.read"
              type="text"
              size="small"
              @click.stop="markAsRead(notification.id)"
            >
              标记已读
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.stop="viewPost(notification)"
            >
              查看帖子
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <div class="empty-content">
          <el-icon size="64" color="#d1d5db"><Bell /></el-icon>
          <h3>暂无消息</h3>
          <p>当有人与你的帖子互动时，你会在这里收到通知</p>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore && filteredNotifications.length > 0" class="load-more">
      <el-button type="text" @click="loadMore" :loading="loadingMore">
        加载更多消息
      </el-button>
    </div>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="showPostDetail"
      :title="selectedPost ? `${selectedPost.author.name} 的帖子` : '帖子详情'"
      width="800px"
      align-center
      destroy-on-close
    >
      <PostDetail
        v-if="selectedPost"
        :post="selectedPost"
        :current-user="currentUser"
        @close="showPostDetail = false"
        @like="handleLike"
        @dislike="handleDislike"
        @add-comment="handleAddComment"
        @add-reply="handleAddReply"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import PostDetail from './PostDetail.vue'
import { Plus, Warning } from '@element-plus/icons-vue'

const props = defineProps({
  currentUser: {
    type: Object,
    required: true
  },
  // 添加帖子数据属性，用于查找对应的帖子
  posts: {
    type: Array,
    default: () => []
  }
})

const showPostDetail = ref(false)
const selectedPost = ref(null)

// 响应式数据
const notifications = ref([])
const currentFilter = ref('all')
const loadingMore = ref(false)
const hasMore = ref(true)

// 计算属性
const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

const likeNotifications = computed(() => {
  return notifications.value.filter(n => n.type === 'like')
})

const dislikeNotifications = computed(() => {
  return notifications.value.filter(n => n.type === 'dislike')
})

const commentNotifications = computed(() => {
  return notifications.value.filter(n => n.type === 'comment')
})

const filteredNotifications = computed(() => {
  if (currentFilter.value === 'all') {
    return notifications.value
  }
  return notifications.value.filter(n => n.type === currentFilter.value)
})

// 方法
const getUnreadCountByType = (type) => {
  return notifications.value.filter(n => n.type === type && !n.read).length
}

const getPostPreview = (content) => {
  if (!content) return '帖子内容'
  return content.length > 30 ? content.substring(0, 30) + '...' : content
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const now = new Date()
  const targetTime = new Date(timestamp)
  const diff = now - targetTime
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return targetTime.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

const filterByType = (type) => {
  currentFilter.value = type
}

const handleNotificationClick = (notification) => {
  // 标记为已读
  if (!notification.read) {
    markAsRead(notification.id)
  }
  
  // 跳转到对应帖子
  viewPost(notification)
}

const markAsRead = (notificationId) => {
  const notification = notifications.value.find(n => n.id === notificationId)
  if (notification) {
    notification.read = true
    ElMessage.success('标记为已读')
  }
}

const markAllAsRead = () => {
  notifications.value.forEach(notification => {
    notification.read = true
  })
  ElMessage.success('全部标记为已读')
}

const viewPost = (notification) => {
  // 根据通知中的帖子ID查找对应的帖子数据
  const post = findPostById(notification.postId)
  if (post) {
    selectedPost.value = post
    showPostDetail.value = true
  } else {
    ElMessage.warning('未找到对应的帖子')
  }
}

// 根据帖子ID查找帖子
const findPostById = (postId) => {
  // 在传入的帖子数据中查找
  if (props.posts && props.posts.length > 0) {
    return props.posts.find(post => post.id === postId)
  }
  
  // 如果在传入的数据中没找到，尝试在模拟数据中查找
  return generateMockPost(postId)
}

// 生成模拟帖子数据
const generateMockPost = (postId) => {
  const mockPosts = {
    1: {
      id: 1,
      author: {
        id: 101,
        name: '张大山',
        avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
        type: 'farmer'
      },
      content: '今年的西红柿长势特别好，采用了新的有机种植技术，果实饱满多汁，欢迎大家来参观选购！',
      keywords: ['西红柿', '有机种植', '新鲜'],
      images: [
        'https://images.unsplash.com/photo-1546470427-e212b7d31075?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80'
      ],
      createTime: '2024-01-15T10:30:00Z',
      likes: 24,
      dislikes: 2,
      userAction: null,
      showComments: false,
      comments: [],
      hotScore: 45.6
    },
    2: {
      id: 2,
      author: {
        id: 102,
        name: '李超市',
        avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
        type: 'buyer'
      },
      content: '急需采购一批有机蔬菜，要求新鲜无农药，有稳定供货能力的农场请联系我！',
      keywords: ['有机蔬菜', '采购', '稳定供货'],
      images: [
        'https://images.unsplash.com/photo-1546470427-e212b7d31075?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80'
      ],
      createTime: '2024-01-15T09:15:00Z',
      likes: 8,
      dislikes: 0,
      userAction: null,
      showComments: false,
      comments: [],
      hotScore: 32.1
    }
  }
  
  return mockPosts[postId] || null
}

// 处理帖子交互
const handleLike = (postId) => {
  console.log('点赞帖子:', postId)
  // 这里可以添加实际的点赞逻辑
  // 更新帖子数据
  const post = findPostById(postId)
  if (post) {
    post.likes += 1
    post.userAction = 'like'
  }
}

const handleDislike = (postId) => {
  console.log('点踩帖子:', postId)
  // 这里可以添加实际的点踩逻辑
  // 更新帖子数据
  const post = findPostById(postId)
  if (post) {
    post.dislikes += 1
    post.userAction = 'dislike'
  }
}

const handleAddComment = (commentData) => {
  console.log('添加评论:', commentData)
  // 这里可以添加实际的评论逻辑
  const { postId, content, author } = commentData
  const post = findPostById(postId)
  if (post) {
    if (!post.comments) {
      post.comments = []
    }
    const newComment = {
      id: Date.now(),
      content,
      author,
      time: new Date().toISOString()
    }
    post.comments.push(newComment)
  }
}

const handleAddReply = (replyData) => {
  console.log('添加回复:', replyData)
  // 这里可以添加实际的回复逻辑
  const { postId, commentId, content, author } = replyData
  const post = findPostById(postId)
  if (post && post.comments) {
    const comment = post.comments.find(c => c.id === commentId)
    if (comment) {
      if (!comment.replies) {
        comment.replies = []
      }
      const newReply = {
        id: Date.now(),
        content,
        author,
        time: new Date().toISOString()
      }
      comment.replies.push(newReply)
    }
  }
}

const refreshNotifications = () => {
  loadNotifications()
  ElMessage.success('消息已刷新')
}

const loadMore = () => {
  loadingMore.value = true
  // 模拟加载更多
  setTimeout(() => {
    const newNotifications = generateMockNotifications(5, notifications.value.length)
    notifications.value.push(...newNotifications)
    loadingMore.value = false
    hasMore.value = notifications.value.length < 50 // 模拟数据限制
  }, 1000)
}

// 初始化加载消息
const loadNotifications = () => {
  // 模拟加载消息数据
  notifications.value = generateMockNotifications(15, 0)
}

// 生成模拟消息数据
const generateMockNotifications = (count, startId = 0) => {
  const types = ['like', 'dislike', 'comment']
  const users = [
    { id: 2, name: '张大山', avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80', type: 'farmer' },
    { id: 3, name: '李超市', avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80', type: 'buyer' },
    { id: 4, name: '王技术员', avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80', type: 'farmer' },
    { id: 5, name: '赵农场主', avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80', type: 'farmer' }
  ]
  
  const postContents = [
    '今年的西红柿长势特别好，采用了新的有机种植技术',
    '急需采购一批有机蔬菜，要求新鲜无农药',
    '分享一个黄瓜种植的病虫害防治经验',
    '新鲜采摘的草莓上市了，纯天然无农药',
    '寻找优质水果供应商，特别是苹果和梨子'
  ]
  
  const commentContents = [
    '看起来真不错！什么价格？',
    '我们农场有大量有机蔬菜供应',
    '好的，已发送好友申请！',
    '这个经验很有用，谢谢分享',
    '请问可以批量采购吗？'
  ]
  
  return Array.from({ length: count }, (_, index) => {
    const type = types[Math.floor(Math.random() * types.length)]
    const fromUser = users[Math.floor(Math.random() * users.length)]
    const postContent = postContents[Math.floor(Math.random() * postContents.length)]
    const commentContent = type === 'comment' ? commentContents[Math.floor(Math.random() * commentContents.length)] : null
    const postId = Math.floor(Math.random() * 2) + 1 // 只生成1或2的帖子ID，对应模拟数据
    
    return {
      id: startId + index + 1,
      type: type,
      fromUser: fromUser,
      postId: postId,
      postContent: postContent,
      commentContent: commentContent,
      read: Math.random() > 0.5,
      timestamp: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    }
  })
}

onMounted(() => {
  loadNotifications()
})
</script>

<style scoped>
.notifications {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notifications-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.notifications-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.notifications-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  background: #f8fafc;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card.active {
  border-color: #4caf50;
  background: #f0f9ff;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  color: white;
}

.stat-icon.all {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.like {
  background: linear-gradient(135deg, #f59e0b, #fbbf24);
}

.stat-icon.dislike {
  background: linear-gradient(135deg, #ef4444, #f87171);
}

.stat-icon.comment {
  background: linear-gradient(135deg, #10b981, #34d399);
}

.stat-info {
  display: flex;
  flex-direction: column;
  position: relative;
}

.stat-count {
  font-size: 1.5rem;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
}

.stat-label {
  font-size: 0.875rem;
  color: #6b7280;
  margin-top: 4px;
}

.unread-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ef4444;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 0.75rem;
  min-width: 18px;
  text-align: center;
  line-height: 1;
}

.notifications-list {
  flex: 1;
  overflow-y: auto;
}

.notifications-container {
  padding: 0;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px 24px;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.notification-item:hover {
  background: #f8fafc;
}

.notification-item.unread {
  background: #f0f9ff;
  border-left: 4px solid #4caf50;
}

.notification-item.unread::before {
  content: '';
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 8px;
  height: 8px;
  background: #4caf50;
  border-radius: 50%;
}

.notification-avatar {
  position: relative;
  flex-shrink: 0;
}

.notification-type-icon {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
  color: white;
  border: 2px solid white;
}

.notification-type-icon.like {
  background: #f59e0b;
}

.notification-type-icon.dislike {
  background: #ef4444;
}

.notification-type-icon.comment {
  background: #10b981;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 0.875rem;
}

.notification-time {
  font-size: 0.75rem;
  color: #9ca3af;
}

.notification-message {
  color: #374151;
  font-size: 0.875rem;
  line-height: 1.4;
  margin-bottom: 4px;
}

.post-preview {
  color: #6b7280;
  font-style: italic;
}

.comment-content {
  background: #f8fafc;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid #e5e7eb;
  color: #4b5563;
  font-size: 0.875rem;
  line-height: 1.4;
  margin-top: 8px;
}

.notification-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex-shrink: 0;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}

.empty-content h3 {
  margin: 16px 0 8px;
  color: #374151;
  font-weight: 600;
}

.empty-content p {
  color: #6b7280;
  margin: 0;
}

.load-more {
  padding: 20px;
  text-align: center;
  border-top: 1px solid #e5e7eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notifications-header {
    padding: 16px 20px;
  }
  
  .notifications-stats {
    grid-template-columns: repeat(2, 1fr);
    padding: 16px 20px;
    gap: 8px;
  }
  
  .stat-card {
    padding: 12px;
  }
  
  .notification-item {
    padding: 16px 20px;
    flex-direction: column;
    gap: 12px;
  }
  
  .notification-actions {
    flex-direction: row;
    justify-content: flex-end;
    width: 100%;
  }
}

@media (max-width: 480px) {
  .notifications-stats {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    justify-content: flex-start;
  }
  
  .notification-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>